package com.theyeasy.dvmini.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * 处理日期时间的工具类<br>
 * 包括格式化和时间字符串之间的转换
 * 
 * @author xian.yq、huang.tao
 * @date 2013-8-7 上午10:26:41
 * @version 0.1.0
 * @copyright yougou.com
 */
public class DateUtil {

	public static final String FORMAT_MONTH = "yyyyMM";
	public static final String FORMAT_DATE = "yyyy-MM-dd";
	public static final String FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss";
	public static final String FORMAT_DATETIME1 = "yyyy-MM-dd HH:mm";
	public static final String FORMAT_TIME = "HH:mm:ss";
	public static final String FORMAT_DATESECOND = "yyMMddHHmmssSSS";
	/** Oct 28, 2017 2:39:52 AM 对应的时间格式*/
	public static final String FORMAT_MMM_dd_yyyy_hh_mm_ss_aa = "MMM dd, yyyy hh:mm:ss aa";

	
	
	
	/**
	 * 将时间格式化成: "yyyyMM"
	 * 
	 * @param date
	 * @return "201406"
	 */
	public static String formatMonth(Date date) {
		return format(date, FORMAT_MONTH);
	}

	/**
	 * 将时间格式化成: "yyyy-MM-dd"
	 * 
	 * @param date
	 * @return "2014-06-27"
	 */
	public static String formatDate(Date date) {
		return format(date, FORMAT_DATE);
	}
	/**
     * 将时间格式化成: "yyyy-MM-dd"
     * 
     * @param date
     * @return "2014-06-27" or null
     */
	public static String formatDate1(Date date) {
        return format1(date, FORMAT_DATE);
    }
	/**
	 * 将时间格式化成: "yyyy/MM/dd"
	 * 
	 * @param date
	 * @return "2014/06/27"
	 */
	public static String format2(Date date) {
		return format(date, "yyyy/MM/dd");
	}

	/**
	 * 将时间格式化成："HH:mm:ss"
	 * 
	 * @param date
	 * @return "16:46:32"
	 */
	public static String formatTime(Date date) {
		return format(date, FORMAT_TIME);
	}
	
	public static String formatTime2Code(Date date){
	    return format(date, "HHmmss");
	}

	/**
	 * 将时间格式化成："yyyy-MM-dd HH:mm:ss"
	 * 
	 * @param date
	 * @return "2014-06-27 16:46:32"
	 */
	public static String formatDateTime(Date date) {
		return format(date, FORMAT_DATETIME);
	}

	/**
	 * 获取当前时间, 并格式化成："yyyy-MM-dd HH:mm:ss" 输出
	 * 
	 * @return "2014-06-27 16:46:32"
	 */
	public static String getCurrentDateTime2Str() {
		return format(new Date(), FORMAT_DATETIME);
	}
	
	/**
	 * 获取当前时间, 并格式化成："yyMMddHHmmssSSS" 输出
	 * 
	 * @return "140627164632111"
	 */
	public static String getCurrentDateTime3Str() {
		return format(new Date(), FORMAT_DATETIME);
	}

	/**
	 * 获取当前时间, 并格式成："yyyyMMddHHmmssSSS" 输出
	 * 
	 * @return "20140627164632"
	 */
	public static String getCurrentDateTime4Str() {
		return format(new Date(), FORMAT_DATESECOND);
	}

	/**
	 * 将<code>format["yyyy-MM-dd"]</code>字符串解析成对象
	 * 
	 * @param date
	 *            "2014-06-27"
	 * @return
	 * @throws Exception
	 */
	public static Date parseDate(String date) throws Exception {
		return parse(date, FORMAT_DATE);
	}
	public static java.util.Date FormatDate(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return (java.util.Date) sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }
	/**
	 * 将<code>format["yyyy-MM-dd HH:mm:ss"]</code>字符串解析成对象
	 * 
	 * @param date
	 *            "2014-06-27 16:46:32"
	 * @return
	 * @throws Exception
	 */
	public static Date parseTime(String date) throws Exception {
		return parse(date, FORMAT_DATETIME);
	}
	
    /**
     * 将<code>format["yyyy-MM-dd HH:mm:ss"]</code>字符串解析成对象
     * 
     * @param date
     *            "2014-06-27 16:46:32"
     * @return
     * @throws Exception
     */
    public static Date parseTime1(String date) throws Exception {
        return parse(date, FORMAT_DATETIME1);
    }
	/**
	 * 将<code>format["yyyy-MM-dd"]</code>字符串 + " 23:59:59" <br>
	 * 然后再解析成对象
	 * 
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public static Date getMaxTimeByStringDate(String date) throws Exception {
		String maxTime = date + " 23:59:59";
		return parse(maxTime, FORMAT_DATETIME);
	}

	public static int getYear(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.YEAR);
	}

	public static int getMonth(java.util.Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.MONTH) + 1;
	}

	public static int getDay(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.DAY_OF_MONTH);
	}

	public static int getHour(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.HOUR_OF_DAY);
	}

	public static int getMinute(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.MINUTE);
	}

	public static int getSecond(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(Calendar.SECOND);
	}

	public static long getMillis(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.getTimeInMillis();
	}

	public static int getWeek(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		dayOfWeek = dayOfWeek - 1;
		if (dayOfWeek == 0) {
			dayOfWeek = 7;
		}
		return dayOfWeek;
	}

	/**
	 * 计算两个日期之间相差的月数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int monthsBetween(Date smdate, Date bdate) {
		try {
			int result = 0;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			smdate = sdf.parse(sdf.format(smdate));
			bdate = sdf.parse(sdf.format(bdate));
			Calendar cal1 = Calendar.getInstance();
			Calendar cal2 = Calendar.getInstance();
			cal1.setTime(smdate);
			cal2.setTime(bdate);
			result = cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
			return result == 0 ? 1 : Math.abs(result);
		} catch (ParseException e) {
			return -1;
		}
	}

	/**
	 * 计算两个日期所占的月数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int monthsBetween2(Date smdate, Date bdate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String d1 = sdf.format(smdate);
		String d2 = sdf.format(bdate);
		long longNum = parseStrTime(d2) - parseStrTime(d1);
		long oneDaylong = 24 * 60 * 60 * 1000;
		long dayNum = longNum / oneDaylong;
		return Integer.valueOf(String.valueOf(dayNum / 30))+1;
		// System.out.println("相差的天数：" + dayNum);
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			smdate = sdf.parse(sdf.format(smdate));
			bdate = sdf.parse(sdf.format(bdate));
			Calendar cal = Calendar.getInstance();
			cal.setTime(smdate);
			long time1 = cal.getTimeInMillis();
			cal.setTime(bdate);
			long time2 = cal.getTimeInMillis();
			long between_days = (time2 - time1) / (1000 * 3600 * 24);
			return Integer.parseInt(String.valueOf(between_days));
		} catch (ParseException e) {
			return -1;
		}
	}

	/**
	 * 计算两个日期之间相差的小时数(去除天数)
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int hoursBetween(Date smdate, Date bdate) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_hours = (time2 - time1) % (1000 * 3600 * 24) / (1000 * 3600);
		return Integer.parseInt(String.valueOf(between_hours));
	}

	/**
	 * 日期相加
	 * 
	 * @param date
	 *            Date
	 * @param day
	 *            int
	 * @return Date
	 */
	public static Date addDate(Date date, int day) {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(getMillis(date) + ((long) day) * 24 * 3600 * 1000);
		return c.getTime();
	}
	
	/**
	 * 今天追加（天）
	 * @param days
	 * @return
	 */
	public static Long addDayByTody(int day) {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, day);
		return c.getTimeInMillis();
	}

	/**
	 * 日期相减
	 * 
	 * @param date
	 *            Date
	 * @param date1
	 *            Date
	 * @return int
	 */
	public static int diffDate(Date date, Date date1) {
		return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000));
	}

	/**
	 * 日期相减 (跨天就算1天)
	 * 
	 * @param date
	 * @param date1
	 * @return
	 */
	public static int diffDay(Date date, Date date1) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		// 设置当前时刻的时钟为0
		c.set(Calendar.HOUR_OF_DAY, 0);
		// 设置当前时刻的分钟为0
		c.set(Calendar.MINUTE, 0);
		// 设置当前时刻的秒钟为0
		c.set(Calendar.SECOND, 0);
		// 设置当前的毫秒钟为0
		c.set(Calendar.MILLISECOND, 0);
		long t = c.getTimeInMillis();

		c.setTime(date1);
		// 设置当前时刻的时钟为0
		c.set(Calendar.HOUR_OF_DAY, 0);
		// 设置当前时刻的分钟为0
		c.set(Calendar.MINUTE, 0);
		// 设置当前时刻的秒钟为0
		c.set(Calendar.SECOND, 0);
		// 设置当前的毫秒钟为0
		c.set(Calendar.MILLISECOND, 0);
		long t1 = c.getTimeInMillis();
		long diff = (t - t1) / (24 * 3600 * 1000);
		return (int) diff;
	}

	/**
	 * 日期相减(返回秒值)
	 * 
	 * @param date
	 *            Date
	 * @param date1
	 *            Date
	 * @return int
	 * @author
	 */
	public static Long diffDateTime(Date date, Date date1) {
		return (Long) ((getMillis(date) - getMillis(date1)) / 1000);
	}

	public static Integer getLeftSeconds(String date) throws Exception {
		Date condition = parse(date, FORMAT_DATETIME);
		long n = condition.getTime();
		long s = new Date().getTime();
		return (int) ((s - n) / 1000);
	}

	/**
	 * 获得时间戳
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String getTime() {
		Date date = new Date();
		return String.valueOf(date.getTime());
	}

	/** 判断日期格式是否正确 */
	public static boolean validateDate(String dateString) {
		// 使用正则表达式 测试 字符 符合 dddd-dd-dd 的格式(d表示数字)
		Pattern p = Pattern.compile("\\d{4}+[-]\\d{2}+[-]\\d{2}+");
		Matcher m = p.matcher(dateString);
		if (!m.matches()) {
			return false;
		}
		// 得到年月日
		String[] array = dateString.split("-");
		int year = Integer.valueOf(array[0]);
		int month = Integer.valueOf(array[1]);
		int day = Integer.valueOf(array[2]);

		if (month < 1 || month > 12) {
			return false;
		}
		int[] monthLengths = new int[] { 0, 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		if (isLeapYear(year)) {
			monthLengths[2] = 29;
		} else {
			monthLengths[2] = 28;
		}
		int monthLength = monthLengths[month];
		if (day < 1 || day > monthLength) {
			return false;
		}
		return true;
	}

	/** 是否是闰年 */
	private static boolean isLeapYear(int year) {
		return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
	}

	public static java.sql.Date parseSqlDate(Date date) {
		if (null == date) {
			return null;
		}
		return new java.sql.Date(date.getTime());
	}

	/**
	 * 时间格式化方法：<br>
	 * 提供将时间转换成指定格式的字符串
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static String format(Date date, String format) {
		String result = "";
		if (null == date) {
			return result;
		}
		DateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}
	public static String format1(Date date, String format) {
        String result = null;
        if (null == date) {
            return result;
        }
        DateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }

	/**
	 * 时间字符串解析方法：<br>
	 * 提供将指定格式的时间字符串解析成时间对象
	 * 
	 * @param date
	 * @param format
	 * @return
	 * @throws Exception
	 */
	public static Date parse(String date, String format) throws Exception {
		DateFormat df = new SimpleDateFormat(format);
		return df.parse(date);
	}

	/**
	 * 砍掉 <b>时分秒</b> 得到 ： yyyy-MM-dd
	 * 
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public static Date getDate(Date date) throws Exception {
		return parseDate(formatDate(date));
	}

	/**
	 * 判断是否为当前日期
	 * 
	 * @param date
	 * @return
	 */
	public static boolean isCurrentDate(Date date) {
		return formatDate(date).equals(formatDate(new Date()));
	}

	/**
	 * 获取上一个月 yyyy-MM
	 */
	public static String getLastMonth(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.MONTH, c.get(Calendar.MONTH) - 1);
		return format(c.getTime(), "yyyy-MM");
	}

	/**
	 * 转换字符串日期 为时间戳(long)
	 * 
	 * @param strTime
	 * @return
	 */
	public static Long parseStrTime(String strTime) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Long time = null;
		try {
			time = df.parse(strTime).getTime();
		} catch (ParseException e) {
			System.out.println("时间戳转换错误！");
			e.printStackTrace();
		}
		return time;
	}
	

	public static void main(String[] args) throws Exception {
		long longNum = parseStrTime("") - parseStrTime("");
		long oneDaylong = 24 * 60 * 60 * 1000;
		long dayNum = longNum / oneDaylong;
		System.out.println("相差的天数：" + dayNum);
		System.out.println("相差的月数：" + dayNum / 30);
	}
	public static Date getStartTime() {  
        Calendar todayStart = Calendar.getInstance();  
        todayStart.set(Calendar.HOUR_OF_DAY, 0);  
        todayStart.set(Calendar.MINUTE, 0);  
        todayStart.set(Calendar.SECOND, 0);  
        todayStart.set(Calendar.MILLISECOND, 0);  
        return todayStart.getTime();  
    }  
    public static Date getnowEndTime() {  
        Calendar todayEnd = Calendar.getInstance();  
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);  
        todayEnd.set(Calendar.MINUTE, 59);  
        todayEnd.set(Calendar.SECOND, 59);  
        todayEnd.set(Calendar.MILLISECOND, 999);  
        return todayEnd.getTime();  
    }
}
